StateFlow and MutableStateFlow are also relatively new additions to coroutines. A StateFlow is a bit like a Flow edition of a ConflatedBroadcastChannel:

  • It can be observed by multiple parties, like a SharedFlow

  • Objects placed into the flow are conflated

The holder of a StateFlow can not only use Flow-like constructs to observe the flow (e.g., collect()) but also can use a value property to get the most-recent object placed onto the StateFlow. Also, once an observer starts observing, it immediately receives the most-recent object, in addition to future ones while it is observing.

The typical way to set up a StateFlow is to use a MutableStateFlow. The constructor-style factory function takes the initial state as a parameter, and you can use the value property to change that state as needed.

Here, we emit the names of the 50 US states onto a MutableStateFlow. With the 200 millisecond delay, the consumer can keep up, and you should see all 50 in the output. But, if you edit this sample and comment out the delay() call, you will find that most of the states get conflated, so the output shows only a subset, often just the first and last.

You can learn more about this in:
Tags:
Run Edit